﻿//-----------------------------------------------------------------------------------------------------------
//  Description:
//     申请书相关
//      
//      
//  Comment                          Date                 Author      Email
//   ----------------------------    -------             -------      -----------------------------------
//  Create                           2012/11/22           wukun       17622690@qq.com
//
// 
//-----------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forest.Cat.Domain.Services.Catalog;
using Forest.Cat.Domain.Services.Applications;
using Forest.Cat.Domain.Services.Compnaies;
using Forest.Cat.Domain.Configuration;
using Forest.Cat.Domain;
using Forest.Cat.Domain.Services;
using Forest.Cat.Domain.Entities;
using Forest.Cat.Domain.Shared;
using Forest.Cat.Web.Models.Jobseekers;
using Forest.Cat.Web.Extensions;
using Forest.Cat.Web.Models.JobApplication;
using Forest.Cat.Web.Models.JobApplications;
using Forest.Cat.Domain.Services.CoverLetters;
using Forest.Cat.Domain.Services.Jobseekers;
using Forest.Cat.Web.Models.Catalog;

namespace Forest.Cat.Web.Controllers
{
    public class JobApplicationController : Controller
    {
        #region Fields
        private readonly IJobPositionService _jobPositionService;
        private readonly IJobseekerService _jobseekerService;
        private readonly IApplicationService _applicationService;
        private readonly ICompanyService _companyService;
        private readonly ILovService _lovService;
        private readonly IResumeService _resumeService;
        private readonly ICoverLetterService _coverLetterService;
        private readonly IWorkContext _workContext;
        #endregion

        #region Constructures
        public JobApplicationController(IJobPositionService jobPositionService,
            IJobseekerService jobseekerService,
            IApplicationService applicationService,
            ICompanyService companyService,
            ILovService lovService,
            IResumeService resumeService,
            ICoverLetterService coverLetterService,
            IWorkContext workContext)
        {
            _jobPositionService = jobPositionService;
            _jobseekerService = jobseekerService;
            _applicationService = applicationService;
            _companyService = companyService;
            _lovService = lovService;
            _resumeService = resumeService;
            _coverLetterService = coverLetterService;
            _workContext = workContext;
        }
        #endregion

        #region Methods

        #region Apply
        public ActionResult Apply(Guid id, String returnUrl)
        {
            var job = _jobPositionService.GetJobPositionById(id);
            var applyModel = PrepareApplyModel(job);
            //如果没有传递返回路径，则默认跳转到SearchJobList页面
            if (String.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Url.Action("SearchJobList", "Catalog");
            }
            applyModel.ReturnUrl = returnUrl;
            return View(applyModel);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Apply(ApplyModel applyModel)
        {
            var application = applyModel.ApplicationModel.ToEntity();
            var job = _jobPositionService.GetJobPositionById(application.JobPositionId);
            //var company = _companyService.GetCompanyById(application.CompanyId);
            application.Id = _applicationService.CreateId;
            //application.JobTitle = job.JobTitle;
            //application.CompanyName = company.CompanyName;
            application.Source = 1;
            application.Status = 1;
            application.DateApplied = DateTime.Now;
            application.JobseekerId = _workContext.CurrentUser.Id;
            application.StartDate = job.StartDate.Value;
            application.EndDate = job.EndDate;
            _applicationService.InsertApplication(application);
            //操作成功后跳转
            var url = Url.Action("Confirmation", new { id = application.Id });
            return Redirect(url);
        }

        [NonAction]
        private ApplyModel PrepareApplyModel(JobPosition job)
        {
            //JobModel
            var jobModel = job.ToModel();
            jobModel.YearsOfExperienceName = _lovService.GetLovName(job.YearsOfExperience.Value);
            jobModel.EducationLevelName = _lovService.GetLovName(job.EducationLevel.Value);
            var company = _companyService.GetCompanyById(job.CompanyId.Value);
            var companyModel = company.ToModel();
            jobModel.CompanyModel = companyModel;
            jobModel.CityName = _lovService.GetLovName(job.City);
            //jobModel.DistrictName = job.District.HasValue ? _lovService.GetLovName(job.District.Value) : String.Empty;
            //DesiredSalaryList
            var desiredSalaryList = _lovService.GetLovList(LovType.SalaryRange).ToList().
                Select(x => new SelectListItem() { Text = x.Name, Value = x.Value.Value.ToString() }).ToList();
            desiredSalaryList.Insert(0, new SelectListItem() { Value = "", Text = "" });
            //ResumeList
            var resumeList = _resumeService.GetResumes(_workContext.CurrentUser.Id).Select(x => x.ToModel());
            //TemplateList
            var templateList = _coverLetterService.GetCoverLetters(_workContext.CurrentUser.Id).
                Select(x => new SelectListItem() { Text = x.Title, Value = x.Id.ToString() }).ToList();
            templateList.Insert(0, new SelectListItem() { Value = "", Text = "" });
            return new ApplyModel()
            {
                ApplicationModel = new ApplicationModel()
                {
                    CompanyId = job.CompanyId.Value,
                    JobPositionId = job.Id,
                },
                JobModel = jobModel,
                DesiredSalaryList = desiredSalaryList,
                ResumeModelList = resumeList,
                TemplateList = templateList
            };
        }

        /// <summary>
        /// 前台AJAX调用后台获取模板内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public String GetTemplateContent(Guid id)
        {
            return _coverLetterService.GetCoverLetterById(id).Body;
        }

        #endregion

        #region Confirmation
        public ActionResult Confirmation(Guid id)
        {
            var applicationModel = _applicationService.GetApplicationById(id).ToModel();
            var jobPosition = _jobPositionService.GetJobPositionById(applicationModel.JobPositionId);
            var company = _companyService.GetCompanyById(applicationModel.CompanyId);
            applicationModel.JobTitle = jobPosition.JobTitle;
            applicationModel.CompanyName = company.CompanyName;
            var confirmationModel = new ConfirmationModel()
            {
                ApplicationModel = applicationModel,
                JobseekerName = _workContext.CurrentUser.FullName
            };
            return View(confirmationModel);
        }

        public PartialViewResult JobList(Guid id)
        {
            var jobList = _jobPositionService.GetRelatedJobList(id).Take(20).ToList();
            return PartialView(jobList.Select(x => PrepareJobModelForView(x)));
        }

        [NonAction]
        private JobPositionModel PrepareJobModelForView(JobPosition job)
        {
            var jobModel = job.ToModel();
            jobModel.YearsOfExperienceName = _lovService.GetLovName(job.YearsOfExperience.Value);
            jobModel.EducationLevelName = _lovService.GetLovName(job.EducationLevel.Value);
            jobModel.CityName = _lovService.GetLovName(job.City);
            //jobModel.DistrictName = job.District.HasValue ? _lovService.GetLovName(job.District.Value) : String.Empty;
            return jobModel;
        }

        #endregion
        #endregion
    }
}
